package com.lgywin.userserver.server;

import com.lgywin.userserver.protobuf.NetProto;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
@ChannelHandler.Sharable
@Slf4j
public class NetProtoHandle extends SimpleChannelInboundHandler<NetProto> {
    @Autowired
    public  NetProHandleToService netProHandleToService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NetProto netProto) throws Exception {
        netProHandleToService.run(ctx,netProto);
    }

    /**
     * 客户端连接
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        log.info("Client Conecting......{}", clientIp);
    }

    /**
     * 客户端断开
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        ctx.fireChannelInactive();
        log.info("Client DisConecting------{}", clientIp);
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("Client exceptionCaught------{}", cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}